/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import entity.User;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author AnBoCa
 */
public class UserSession {

    private HttpSession session;
    private FacesContext fc;
    private ExternalContext ex;
    /**
     * Creates a new instance of UserSession
     */
    public UserSession() {
        //revisa la session, si no se encuentra redirecciona
        fc=FacesContext.getCurrentInstance();
        ex=fc.getExternalContext();
        session=(HttpSession) ex.getSession(true);
    }
    
    public String isSessionValid(){
        if (session.getAttribute("user")==null){
            try {
                ex.redirect(ex.getRequestContextPath()+"/login.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserSession.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        User user=(User) session.getAttribute("user");
        if (user==null){
            try {
                ex.redirect(ex.getRequestContextPath()+"/login.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserSession.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return user.getName();
    }
}
